<!--
 * @Description: 登录页面
 * @Version: 1.0
 * @Autor: JiaJun Wu
 * @Date: 2021-11-04 16:21:12
 * @LastEditors: jiajun wu
 * @LastEditTime: 2021-12-01 10:20:01
-->
<!-- 登录页面 -->
<template>
  <div class="main">
    <a-form id="formLogin" class="user-layout-login" @submit="handleSubmit" :model="formRef">
      <a-tabs
        :activeKey="formRef.type"
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick"
      >
        <!-- 账户密码登录 -->
        <a-tab-pane key="userName" :tab="$t('user.login.tab-login-credentials')">
          <a-alert
            v-if="isLoginError"
            type="error"
            showIcon
            style="margin-bottom: 24px"
            :message="$t('user.login.message-invalid-credentials')"
          />
          <a-form-item v-bind="validateInfos.username">
            <a-input
              size="large"
              type="text"
              :placeholder="$t('user.login.username.placeholder')"
              v-model:value="formRef.username"
            >
              <template #prefix>
                <UserOutlined :style="{ color: 'rgba(0,0,0,.25)' }" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item v-bind="validateInfos.password">
            <a-input-password
              size="large"
              :placeholder="$t('user.login.password.placeholder')"
              v-model:value="formRef.password"
            >
              <template #prefix>
                <LockOutlined :style="{ color: 'rgba(0,0,0,.25)' }" />
              </template>
            </a-input-password>
          </a-form-item>
        </a-tab-pane>
        <!-- 手机号登录 -->
        <a-tab-pane key="phone" :tab="$t('user.login.tab-login-mobile')">
          <a-form-item v-bind="validateInfos.mobile">
            <a-input
              size="large"
              type="text"
              :placeholder="$t('user.login.mobile.placeholder')"
              v-model:value="formRef.mobile"
            >
              <MobileOutlined :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-item>

          <a-row :gutter="16">
            <a-col class="gutter-row" :span="16">
              <a-form-item v-bind="validateInfos.captcha">
                <a-input
                  size="large"
                  type="text"
                  :placeholder="
                    $t('user.login.mobile.verification-code.placeholder')
                  "
                  v-model:value="formRef.captcha"
                >
                  <MailOutlined :style="{ color: 'rgba(0,0,0,.25)' }" />
                </a-input>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-button
                class="getCaptcha"
                tabindex="-1"
                :disabled="state.smsSendBtn"
                @click.stop.prevent="getCaptcha"
              >
                {{
                (!state.smsSendBtn &&
                $t("user.register.get-verification-code")) ||
                state.time + " s"
                }}
              </a-button>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>

      <a-form-item v-bind="validateInfos.rememberMe">
        <a-checkbox
          v-model:checked="formRef.rememberMe"
          style="float: left"
        >{{ $t("user.login.remember-me") }}</a-checkbox>
        <router-link to="/" class="forge-password" style="float: right">
          {{
          $t("user.login.forgot-password")
          }}
        </router-link>
      </a-form-item>

      <a-form-item style="margin-top: 24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
        >{{ $t("user.login.login") }}</a-button>
      </a-form-item>

      <div class="user-login-other">
        <span>{{ $t("user.login.sign-in-with") }}</span>
        <a>
          <AlipayCircleOutlined />
        </a>
        <a>
          <TaobaoCircleOutlined />
        </a>
        <a>
          <WeiboCircleOutlined />
        </a>
        <router-link class="register" :to="{ name: 'register' }">{{ $t("user.login.signup") }}</router-link>
      </div>
    </a-form>
  </div>
</template>

<script lang="ts">
import { Form } from "ant-design-vue";
import { defineComponent, UnwrapRef, reactive, ref } from "vue";
import { LoginFormStateStruct } from "@/interface/user";
import { useI18n } from "vue-i18n";
import {
  MobileOutlined,
  MailOutlined,
  AlipayCircleOutlined,
  TaobaoCircleOutlined,
  WeiboCircleOutlined,
  UserOutlined,
  LockOutlined,
} from "@ant-design/icons-vue";
import { useGetCaptcha } from "../helper";
import { useStore } from "vuex";

export default defineComponent({
  components: {
    MobileOutlined,
    UserOutlined,
    MailOutlined,
    AlipayCircleOutlined,
    TaobaoCircleOutlined,
    WeiboCircleOutlined,
    LockOutlined,
  },
  setup() {
    const useForm = Form.useForm;
    const { t } = useI18n();
    const isLoginError = ref(false);
    const store = useStore();

    // #region 表单相关
    const formRef: UnwrapRef<LoginFormStateStruct> = reactive({
      rememberMe: false,
      username: "",
      password: "",
      mobile: "",
      captcha: "",
      type: "userName",
    });
    /** 表单 */
    const handleSubmit = (e: Event) => {
      e.preventDefault();
      state.loginBtn = true;
      const validateFieldsKey =
        formRef.type === "userName"
          ? ["username", "password"]
          : ["mobile", "captcha"];

      validate(validateFieldsKey)
        .then(async () => {
          // formRef.password = encryptByMd5(formRef.password);
          state.loginBtn = true;

          store.dispatch("login", formRef).then((res) => {
            console.log(res, "res--");
          });
          // state.loginBtn = false;
        })
        .catch((e) => {
          state.loginBtn = false;
        });
    };

    /** 标签页 */
    const handleTabClick = (key: string) => {
      formRef.type = key;
    };

    const state = reactive({
      time: 60,
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      smsSendBtn: false,
    });

    const handleUsernameOrEmail = (_rule: any, value: string) => {
      const regex =
        /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      if (regex.test(value)) {
        state.loginType = 0;
      } else {
        state.loginType = 1;
      }
      return Promise.resolve();
    };
    const rulesRef = reactive({
      rememberMe: [{ trigger: "checked" }],
      username: [
        {
          required: true,
          message: t("user.userName.required"),
        },
        {
          validator: handleUsernameOrEmail,
          trigger: "change",
        },
      ],
      password: [{ required: true, message: t("user.password.required") }, {}],
      mobile: [
        {
          required: true,
          pattern: /^1[345678]\d{9}$/,
          message: t("user.login.mobile.placeholder"),
          validateTrigger: "change",
        },
      ],
      captcha: [
        {
          required: true,
          message: t("user.verification-code.required"),
          validateTrigger: "blur",
        },
      ],
    });
    const { validate, validateInfos } = useForm(formRef, rulesRef);

    //#region 获取验证码
    const getCaptcha = (e: Event) => {
      useGetCaptcha(e, validate, state, formRef, null);
    };
    //#endregion

    return {
      isLoginError,
      state,
      handleSubmit,
      formRef,
      handleTabClick,
      validateInfos,
      getCaptcha,
    };
  },
});
</script>
<style lang='less' scoped>
@import url('@/styles/index.less');

.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .anticon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
